//et
#import "AMapNavViewController.h"
#import <AudioToolbox/AudioToolbox.h>
#import "MANaviAnnotionView.h"

@interface AMapNavViewController ()<AMapNaviViewControllerDelegate>
{
    AMapNaviPoint *_endPoint;
    AMapNaviPoint *_startPoint;
    MAUserLocation *_userLocation;
    NSMutableArray *_poiAnnatation;
    CLLocationManager *_locationManager;
}
@property(nonatomic,weak) MAMapView *mapView;

@property(nonatomic,strong) AMapNaviViewController *naviViewController;
@end

@implementation AMapNavViewController


-(instancetype)init{
    if (self=[super init]) {
        _startPoint = [AMapNaviPoint locationWithLatitude:39.989614 longitude:116.481763];
        _endPoint   = [AMapNaviPoint locationWithLatitude:39.983456 longitude:116.315495];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initNavigationItem];
    [self initProperties];
    
    [self initMapView];
    
    [self initNaviManager];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    self.title=NSLocalizedString(@"高德地图",nil);
    
    self.navigationController.navigationBar.barStyle=UIBarStyleDefault;
    self.navigationController.navigationBar.translucent          =NO;
    self.navigationController.toolbar.barStyle      =UIBarStyleDefault;
    self.navigationController.toolbar.translucent                =NO;
    self.navigationController.toolbarHidden                      =NO;
    
    [self initToolBar];
    [self setupMapView];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
}
-(void)navigationControllerDefault{
    self.navigationController.navigationBar.barStyle=UIBarStyleDefault;
    self.navigationController.navigationBar.translucent=YES;
    self.navigationController.toolbar.barStyle=UIBarStyleDefault;
    self.navigationController.toolbar.translucent=YES;
    self.navigationController.toolbarHidden=YES;
    
}
-(void)initToolBar{
    UIBarButtonItem *flexbleItem=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    UISegmentedControl *segmentedControl=[[UISegmentedControl alloc] initWithItems:
                                          [NSArray arrayWithObjects:
                                           @"餐饮",
                                           @"酒店",
                                           @"电影",
                                           nil]];
   // [segmentedControl addTarget:self action:@selector() forControlEvents:UIControlEventValueChanged];
    UIBarButtonItem *searchTypeItem=[[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
    self.toolbarItems=[NSArray arrayWithObjects:flexbleItem,searchTypeItem ,flexbleItem,nil];
}
-(void)initNavigationItem{

    UIBarButtonItem *leftBar=[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Back",nil) style:UIBarButtonItemStylePlain target:self action:@selector(goBack)];
    
    self.navigationItem.leftBarButtonItem=leftBar;
}
-(void)goBack{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND,0), ^{
        //
    });
    [self.naviManager stopNavi];
    [self.naviManager dismissNaviViewControllerAnimated:YES];
    
    [self.navigationController popViewControllerAnimated:YES];
    [self navigationControllerDefault];
}
-(void)initProperties{
    _poiAnnatation=[[NSMutableArray alloc] init];
}

-(void)initSearch{
    if (self.search==nil) {
        self.search=[[AMapSearchAPI alloc] init];
        self.search.delegate=self;
    }
}

-(void)initNaviManager{
    if (self.naviManager==nil) {
        self.naviManager=[[AMapNaviManager alloc] init];
    }
    [self.naviManager setDelegate:self];
}


-(void)initNaviViewController{
    if (self.naviViewController==nil) {
        self.naviViewController=[[AMapNaviViewController alloc] initWithMapView:_mapView delegate:self];
    }
    [self.naviViewController setDelegate:self];
}


-(void)initMapView{
    if (_mapView==nil) {
        
        _mapView=[[SharedMapView sharedInstance] mapView];
    }
    
    [[SharedMapView sharedInstance] stashMapViewStatus];
    
    [_mapView setFrame:self.view.bounds];
    
    [_mapView setDelegate:self];
}

-(void)setupMapView{
    [self.mapView setDelegate:self];
    [self.mapView setFrame:self.view.bounds];
    [self.view addSubview:self.mapView];
    
    [self initLocationManager];
    
    self.mapView.showsUserLocation=YES;
    self.mapView.userTrackingMode=1;
    if ([_poiAnnatation count]) {
        [self showPOIAnnotations];
    }
}

-(void)initLocationManager{
    _locationManager=[[CLLocationManager alloc] init];
    if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined) {
        if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            [_locationManager performSelector:@selector(requestAlwaysAuthorization)];
        }
        if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [_locationManager performSelector:@selector(requestWhenInUseAuthorization)];
        }
    }
}

-(void)cleanMapView{
    
    [self.mapView setShowsUserLocation:NO];
    
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView removeOverlays:self.mapView.overlays];
    
    [self.mapView setDelegate:nil];
    
    [[SharedMapView sharedInstance] popMapViewStatus];
}
-(void)searchAction:(UISegmentedControl *)segmentedControl{
    
    //AMapSearchServices *request=[[AMapSearchAPI alloc] init];
    if (_userLocation) {
        
    }
}

-(void)startEmulatorNavi{
    [self calculateRoute];
}

-(void)calculateRoute{
    
    NSArray *startPoints = @[_startPoint];
    NSArray *endPoints   = @[_endPoint];
    
    [self.naviManager calculateDriveRouteWithStartPoints:startPoints endPoints:endPoints wayPoints:nil drivingStrategy:0];
}

-(void)showPOIAnnotations{
    [self.mapView addAnnotations:_poiAnnatation];
    if (_poiAnnatation.count==1) {
        self.mapView.centerCoordinate=[(MAPointAnnotation *)_poiAnnatation[0] coordinate];
    }else{
        [self.mapView showAnnotations:_poiAnnatation animated:YES];
    }
}
-(void)mapView:(MAMapView *)mapView annotationView:(MAAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control{
    if ([view.annotation isKindOfClass:[MAPointAnnotation class]]) {
        
        MAPointAnnotation *annotation=(MAPointAnnotation *)view.annotation;
        
        _endPoint=[AMapNaviPoint locationWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];
        [self startEmulatorNavi];
    }
}

-(MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation{
    if ([annotation isKindOfClass:[MAPointAnnotation class]]){
        static NSString *pointReuseIndetifier=@"poiIdentifier";
        MANaviAnnotionView *annotationView=(MANaviAnnotionView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
        if (annotationView==nil) {
            annotationView=[[MANaviAnnotionView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndetifier];
        }
        annotationView.canShowCallout=YES;
        annotationView.draggable=NO;
        
        return annotationView;
    }
    return nil;
}


-(void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error{
    NSLog(@"SearchError:{%@}",error.localizedDescription);
}


//-(void)

-(void)naviManager:(AMapNaviManager *)naviManager error:(NSError *)error{
    NSLog(@"error:{%@}",error.localizedDescription);
}

-(void)naviManager:(AMapNaviManager *)naviManager didPresentNaviViewController:(UIViewController *)naviViewController{
    NSLog(@"didPresentNaviViewController");
    [self naviManager:naviManager didPresentNaviViewController:naviViewController];
    [self.naviManager startEmulatorNavi];
}

-(void)naviManager:(AMapNaviManager *)naviManager didDismissNaviViewController:(UIViewController *)naviViewController{
    NSLog(@"didDismissNaviViewController");
    [self setupMapView];
}

-(void)naviManagerOnCalculateRouteSuccess:(AMapNaviManager *)naviManager{
    if (self.naviViewController==nil) {
        [self initNaviViewController];
    }
    [self cleanMapView];
    [self.naviManager presentNaviViewController:self.naviViewController animated:YES];
}

-(void)naviManager:(AMapNaviManager *)naviManager onCalculateRouteFailure:(NSError *)error{
    NSLog(@"onCalculateRouteFailure");
}

-(void)naviManagerNeedRecalculateRouteForYaw:(AMapNaviManager *)naviManager{
    NSLog(@"NeedReCalculateRouteForYaw");
}

-(void)naviManager:(AMapNaviManager *)naviManager didStartNavi:(AMapNaviMode)naviMode{
    NSLog(@"didStartNavi");
}

-(void)naviManagerDidEndEmulatorNavi:(AMapNaviManager *)naviManager{
    NSLog(@"didEndEmulatorNavi");
}

-(void)naviManagerOnArrivedDestination:(AMapNaviManager *)naviManager{
    NSLog(@"OnArrivedDestination");
}

-(void)naviManager:(AMapNaviManager *)naviManager didUpdateNaviLocation:(AMapNaviLocation *)naviLocation{
   // NSLog(@"didUpdateNaviLocation");
}

-(void)naviManager:(AMapNaviManager *)naviManager didUpdateNaviInfo:(AMapNaviInfo *)naviInfo{
    NSLog(@"didUpdateNaviInfo");
    [self naviManager:naviManager didUpdateNaviInfo:naviInfo];
}

-(BOOL)naviManagerGetSoundPlayState:(AMapNaviManager *)naviManager{
    return 0;
}

-(void)naviManager:(AMapNaviManager *)naviManager playNaviSoundString:(NSString *)soundString soundStringType:(AMapNaviSoundType)soundStringType{
    if (soundStringType==AMapNaviSoundTypePassedReminder) {
        
        AudioServicesPlaySystemSound(1009);
        
    }else{
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND,0), ^{
            //讯飞语音接入
        });
    }
}

#pragma mark -AManNaviViewController Delegate

-(void)naviViewControllerCloseButtonClicked:(AMapNaviViewController *)naviViewController{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        //停止讯飞语音
    });
    //停止到导航
    [self.naviManager stopNavi];
    //取消展示导航视图控制器
    [self.naviManager dismissNaviViewControllerAnimated:YES];
}

-(void)naviViewControllerMoreButtonClicked:(AMapNaviViewController *)naviViewController{
    //判断地图的方向
    if (self.naviViewController.viewShowMode==AMapNaviViewShowModeCarNorthDirection) {
        
        self.naviViewController.viewShowMode=AMapNaviViewShowModeMapNorthDirection;
        
    }else{
        
        self.naviViewController.viewShowMode=AMapNaviViewShowModeCarNorthDirection;
        
    }
}

-(void)naviViewControllerTurnIndicatorViewTapped:(AMapNaviViewController *)naviViewController{
    [self.naviManager readNaviInfoManual];
}

-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation{
    
}
@end
